package com.yupi.project.mq.deadQueue;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class RabbitMQExample {
    private static final String QUEUE_NAME = "common_queue";
    private static final String DEAD_LETTER_QUEUE_NAME = "dead_queue";
    private static final String EXCHANGE_NAME = "common_exchange";
    private static final String DEAD_LETTER_EXCHANGE_NAME = "dead_exchange";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtils.getChannel();
        
        // 创建死信队列和交换机
        channel.exchangeDeclare(DEAD_LETTER_EXCHANGE_NAME, "direct");
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        channel.queueDeclare(DEAD_LETTER_QUEUE_NAME, true, false, false, null);
        channel.queueBind(DEAD_LETTER_QUEUE_NAME, DEAD_LETTER_EXCHANGE_NAME, DEAD_LETTER_QUEUE_NAME);
        
        // 创建正常队列，并设置死信交换机及死信队列
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", DEAD_LETTER_QUEUE_NAME);
        channel.queueDeclare(QUEUE_NAME, true, false, false, arguments);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

        AMQP.BasicProperties properties = null;
        // 加上过期时间
        properties = new AMQP.BasicProperties().builder().expiration("30000").build();
        
        // 定时发送消息到正常队列
        String message = "定时消息通知";
        channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, properties, message.getBytes(StandardCharsets.UTF_8));
        System.out.println("发送定时消息成功");
        
        // 关闭连接
        channel.close();
    }
}